<?php

namespace App\Service;

use App\Models\Book;
use Exception;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class BqsService
{
    protected static string $url = 'https://api.book.bbdaxia.com/';
    public function __construct()
    {

    }

    /**
     * @throws Exception
     */
    public static function top250($category = '玄幻')
    {

        return self::requestHandle('hot',[
            'category' => $category
        ]);
    }

    /**
     * @throws Exception
     */
    public static function searchByName($name)
    {
        $data = self::requestHandle('book',[
            'name' => $name
        ]);
        if (!$data){
            throw new  Exception('暂无数据');
        }

        $list = self::requestHandle($data[0]['url']);
        if (!$list['list']) {
            throw new  Exception('暂无章节数据');
        }
        return  $list['list'];
    }

    /**
     * @throws Exception
     */
    public static function getReadInfo($url)
    {
        return self::requestHandle($url);
    }

    /**
     * @throws Exception
     */
    private static function requestHandle($page, $params=[])
    {
        $response = Http::get(self::$url.$page,$params)->json();
        if ($response['code'] != 1) {
            throw new Exception($response['msg']);
        }
        return $response['data'];
    }
//    public static function downloadImg($remoteImageUrl): string
//    {
//        // 获取远程图片的内容
//        $imageContents = file_get_contents($remoteImageUrl);
//
//        // 生成一个本地存储的文件名
//        $localFileName = 'bqs/' . basename($remoteImageUrl).'.jpg';
//
//        // 将远程图片保存到本地 storage
//        Storage::put($localFileName, $imageContents);
//
//        return $localFileName;
//    }
    public static function downloadImg($url): string
    {
        $response = Http::get($url);
        $filename = md5($url).'.jpg';
        Storage::disk('public')->put($filename, $response->body());
        return $filename;
    }
}
